<template src="./template.html"></template>

<script>
/* global moment */
import CourseMixins from '../mixins'
import ResizeMixin from 'mixins/resize'
import { PAGE_CONFIG, ORDER_SORTS } from 'common/consts'
import { COL_INDEXS } from './consts'
import { getCourseUserList, deleteCourseUser, getCourseStuGroup } from './models'
import AddTrainee from './add-trainee'

export default {
  components: { AddTrainee },
  mixins: [ResizeMixin, CourseMixins],
  data() {
    return {
      COL_INDEXS,
      isPageLoading: false,
      groupList: [],

      tableList: [],
      PAGE_CONFIG: PAGE_CONFIG,
      pageNo: PAGE_CONFIG.defaultPageNo,
      pageSize: PAGE_CONFIG.defaultPageSize,
      totalCount: 0,
      filterForm: {
        q: '',
        groupId: '',
        orders: []
      },

      addDialogVisible: false,
    };
  },

  methods: {
    indexMethod(index) {
      return (this.pageNo - 1) * this.pageSize + index + 1;
    },
    $sortChange({ column, prop, order }) {
      console.log(column, prop, order)
      const orderIdx = this.filterForm.orders.findIndex(it => it.column === prop)
      const params = {
        column: prop,
        order: ORDER_SORTS[order]
      }
      if (orderIdx <= -1) {
        if (order) {
          this.filterForm.orders.push(params)
        }
      } else {
        if (order) {
          this.$set(this.filterForm.orders, orderIdx, params)
        } else {
          this.filterForm.orders.splice(orderIdx, 1)
        }
      }
      this.$getTableList()
    },
    async $getCourseStuGroup() {
      const params = {
        courseId: this.courseId,
        limit: 99999,
        page: 1,
      };
      try {
        const { data } = await getCourseStuGroup(params);
        this.groupList = data.list
      } catch (err) {
        this.$message.error(err.message || '获取分组出错')
      }
    },
    $handleRecord(row) {
      this.$router.push({
        name: 'curriculum.manager.record',
        query: {
          courseId: this.courseId,
          userId: row.userId,
          nickName: row.nickName
        }
      })
    },
    $handleGroup() {
      this.$router.push({
        name: 'curriculum.manager.group-trainee',
        params: {
          courseId: this.courseId
        }
      })
    },
    $handleExamine() {
      this.$router.push({
        name: 'curriculum.manager.examine',
        params: {
          courseId: this.courseId
        }
      })
    },
    $handleImport() {
      this.$router.push({
        name: 'curriculum.manager.import',
        params: {
          courseId: this.courseId
        }
      })

    },
    $search() {
      this.pageNo = 1
      this.$getTableList()
    },
    // 删除请求
    async $handleDeleteHttp(params) {
      try {
        this.isPageLoading = true
        await deleteCourseUser(params)
        this.$message.success('删除成功')
        // if (this.tableData.length === 1) {
        //   this.pageNo = this.pageNo > 1 ? this.pageNo - 1 : this.pageNo
        // }
        this.$search()
      } catch (err) {
        this.isPageLoading = false
        this.$message.error(err.retDesc || err.message || '删除出错')
      }
    },
    // 删除点击
    $handleDelete(row) {
      const params = {
        id: row.id
      }
      this.$confirm('你确定要移除该学员吗？', {
        type: 'warning',
        confirmButtonText: '删除',
      }).then(() => {
        this.$handleDeleteHttp(params)
      }).catch(() => {
        console.log('取消');
      });
    },
    $handleEdit(row) {
      this.$router.push(`/curriculum/manager/info/${row.id}`)
    },
    async $getTableList() {
      this.isPageLoading = true;
      const params = {
        ...this.filterForm,
        limit: this.pageSize,
        page: this.pageNo,
        courseId: this.courseId
      };
      delete params.orders
      try {
        const { data } = await getCourseUserList(params);
        this.tableList = (data.list || []).map(item => ({
          ...item,
          // passRateT: item.passRate ? `${item.passRate}%` : '',
          // practiceCountT: item.practiceCount ? `${item.practiceCount}次` : '',
          passRateT: item.passRate,
          practiceCountT: item.practiceCount || 0,
          lessonProcess: item.totalLessonNum ? (((item.totalLessonNum - item.unfinishLessonNum) / item.totalLessonNum) * 100).toFixed(2) : 0,
          joinTime: moment(item.joinTime).format('YYYY-MM-DD HH:mm')
        }))
        this.totalCount = data.total
        this.isPageLoading = false;
      } catch (err) {
        this.isPageLoading = false;
        this.$message.error(err.message || '拉取信息失败')
      }
    },
    $handlePageChange() {
      this.$getTableList();
    },
    $addSuccess(cb) {
      this.$search()
      this.addDialogVisible = false
      if (cb) {
        cb()
      }
    }
  },
  created() {
    this.$getTableList()
    this.$getCourseStuGroup()
  },
};
</script>
